package com.sunl.mall.ali.mq.model.transaction;

import com.aliyun.openservices.ons.api.SendResult;
import com.sunl.mall.ali.mq.model.RocketMqSendResult;

public class RocketMqTransactionSendResult extends RocketMqSendResult {
    /**
     * 本地事务异常
     */
    private Throwable localTransactionThrowable;
    /**
     * 半事务消息是否发送成功
     */
    private boolean sendHalfMsgOk;

    public RocketMqTransactionSendResult(boolean success, String messageId, String topic) {
        super(success, messageId, topic);
    }

    public RocketMqTransactionSendResult() {
    }

    public static RocketMqTransactionSendResult successIfNotNull(SendResult sendResult) {
        if (sendResult != null) {
            return new RocketMqTransactionSendResult(true, sendResult.getMessageId(), sendResult.getTopic());
        }
        return fail();
    }

    private static final RocketMqTransactionSendResult FAIL_INSTANCE = new RocketMqTransactionSendResult(false, null, null) {

        public void setMessageId(String messageId) {
            throw new UnsupportedOperationException();
        }

        public void setSuccess(boolean success) {
            throw new UnsupportedOperationException();
        }

        public void setTopic(String topic) {
            throw new UnsupportedOperationException();
        }
    };

    public static RocketMqTransactionSendResult fail() {
        return FAIL_INSTANCE;
    }

    public Throwable getLocalTransactionThrowable() {
        return localTransactionThrowable;
    }

    public void setLocalTransactionThrowable(Throwable localTransactionThrowable) {
        this.localTransactionThrowable = localTransactionThrowable;
    }

    public boolean isSendHalfMsgOk() {
        return this.sendHalfMsgOk;
    }

    public void setSendHalfMsgOk(boolean sendHalfMsgOk) {
        this.sendHalfMsgOk = sendHalfMsgOk;
    }

    public boolean hasLocalTransactionThrowable() {
        return getLocalTransactionThrowable() != null;
    }
}
